package com.xjd.edu.logging;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * 自定义 Encoder 以实现日志脱敏（打码）
 *
 * @author wangyu
 * @created 2025/3/15 10:12
 * @see PatternLayoutEncoder
 */
public class EduPatternLayoutEncoder extends PatternLayoutEncoder {

    final boolean desensitized = true;

    /**
     * @param event
     * @return
     * @see ch.qos.logback.classic.spi.LoggingEvent
     * @see EduLoggingEventWrapper
     */
    @Override
    public byte[] encode(ILoggingEvent event) {
        if (desensitized) {
            return convertToBytes(layout.doLayout(new EduLoggingEventWrapper(event)));
        } else {
            return convertToBytes(layout.doLayout(event));
        }
    }

    private byte[] convertToBytes(String s) {
        if (this.getCharset() == null) {
            return s.getBytes();
        } else {
            return s.getBytes(this.getCharset());
        }
    }

}
